import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: () => import('../views/layout/LayoutView.vue'),
      redirect: '/dashboard',
      meta: { requiresAuth: true },
      children: [
        {
          path: 'dashboard',
          name: 'Dashboard',
          component: () => import('../views/dashboard/DashboardView.vue'),
          meta: { title: '数据概览' }
        },
        {
          path: 'activities',
          name: 'Activities',
          component: () => import('../views/activity/ActivityView.vue'),
          meta: { title: '活动管理' }
        },
        {
          path: 'videos',
          name: 'Videos',
          component: () => import('../views/video/VideoView.vue'),
          meta: { title: '视频管理' }
        },
        {
          path: 'products',
          name: 'Products',
          component: () => import('../views/product/ProductView.vue'),
          meta: { title: '商品管理' }
        },
        {
          path: 'orders',
          name: 'Orders',
          component: () => import('../views/order/OrderView.vue'),
          meta: { title: '订单管理' }
        },
        {
          path: 'analytics',
          name: 'Analytics',
          component: () => import('../views/analytics/AnalyticsView.vue'),
          meta: { title: '数据分析' }
        },
        {
          path: 'fans',
          name: 'Fans',
          component: () => import('../views/fans/FansView.vue'),
          meta: { title: '粉丝管理' }
        }
      ]
    },
    {
      path: '/dashboard',
      redirect: '/'
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import('../views/NotFoundView.vue')
    }
  ]
})

// 从URL参数获取并保存认证信息
const initAuthFromURL = () => {
  const urlParams = new URLSearchParams(window.location.search)
  const token = urlParams.get('token')
  const userType = urlParams.get('userType')
  const userInfo = urlParams.get('userInfo')
  
  console.log('🔍 检查URL参数:', { 
    token: token ? `长度:${token.length}` : '不存在', 
    userType: userType || '不存在' 
  })
  
  if (token && userType) {
    console.log('🔑 从URL参数获取认证信息:')
    console.log('   Token:', token.substring(0, 20) + '...')
    console.log('   UserType:', userType)
    
    // 保存到localStorage - 统一使用 token 作为键名
    localStorage.setItem('token', token)
    localStorage.setItem('userType', userType)
    if (userInfo) {
      localStorage.setItem('userInfo', userInfo)
    }
    
    // 清除URL中的认证参数
    const cleanUrl = window.location.pathname
    console.log('🧹 清除URL参数，跳转到:', cleanUrl)
    window.history.replaceState({}, '', cleanUrl)
    
    console.log('✅ 认证信息已保存到localStorage')
    console.log('📝 存储的token:', localStorage.getItem('token')?.substring(0, 20) + '...')
    console.log('📝 存储的userType:', localStorage.getItem('userType'))
  }
}

// 在路由守卫之前初始化认证信息
initAuthFromURL()

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem('token')
  const userType = localStorage.getItem('userType')
  
  console.log('🔐 路由守卫检查:', {
    path: to.path,
    token: token ? `长度:${token.length}` : '不存在',
    userType: userType || '不存在'
  })

  if (to.meta.requiresAuth) {
    if (!token) {
      console.log('❌ 未找到token，跳转到登录页')
      ElMessage.warning('请先登录')
      const redirectUrl = `http://localhost:5173/login?redirect=${encodeURIComponent(window.location.href)}`
      window.location.href = redirectUrl
      return
    }
    
    if (userType !== 'anchor') {
      console.log('❌ 用户类型不正确:', userType)
      ElMessage.warning('您没有权限访问管理后台')
      window.location.href = 'http://localhost:5173'
      return
    }

    console.log('✅ 认证通过，允许访问:', to.path)
    next()
  } else {
    next()
  }
})

export default router